package com.xiaoyun.alllearning.config;

import com.github.benmanes.caffeine.cache.Caffeine;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.caffeine.CaffeineCache;
import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@EnableCaching
@Configuration
@Slf4j
public class CaffeineCacheConfig {
    /**
     * CacheManager 实现类
     *
     * @return
     */
    @Bean("cacheManager")
    public CacheManager cacheManager() {
        SimpleCacheManager cacheManager = new SimpleCacheManager();

        List<CaffeineCache> cache = new ArrayList<>();

        cache.add(new CaffeineCache("users-cache",
                Caffeine.newBuilder()
                        .maximumSize(1000)
                        .expireAfterAccess(120, TimeUnit.SECONDS)
                        .build()));
        cacheManager.setCaches(cache);
        return cacheManager;
    }

}
